<template>
  <view class="goods-container">
    <!-- 商品列表 -->
    <scroll-view class="goods-scroll" scroll-y @scrolltolower="loadMore">
      <view class="goods-list">
        <view class="goods-item" v-for="(item, index) in goodsList" :key="index"
              @click="goToGoodsDetail(item)">
          <image class="goods-image" :src="item.pic" mode="aspectFill"></image>
          <view class="goods-info">
            <text class="goods-name">{{ item.prodName || '-' }}</text>
            <!--            <text class="goods-desc">{{ item.brief || '暂无商品描述' }}</text>-->
            <view class="goods-meta">
              <text class="meta-item">单位：{{ item.units || '-' }}</text>
              <!--              <text class="meta-item">排序：{{ item.weight || 0 }}</text>-->
              <text class="meta-item">销量：{{ item.soldNum || 0 }}</text>
            </view>
            <view class="goods-meta">
              <text class="meta-item">折扣：{{ formatDiscount(item.alumniDiscount) }}</text>
              <text class="meta-item">返佣：{{ formatRebate(item.rebate) }}</text>
            </view>
            <view class="goods-bottom">
              <text class="goods-price">¥{{ formatPrice(item.price) }}</text>
              <text class="goods-stock">库存：{{ item.totalStocks || 0 }}</text>
            </view>
          </view>
          <view class="goods-status">
            <text class="status-text" :class="{ active: item.status === 1 }">
              {{ item.status === 1 ? '上架中' : '已下架' }}
            </text>
            <view class="item-actions">
              <view class="action-btn edit" @click.stop="editGoods(item)">
                <u-icon name="edit-pen" size="28" color="#4182bb"></u-icon>
              </view>
              <view class="action-btn delete" @click.stop="deleteGoods(item)">
                <u-icon name="trash" size="28" color="#ff6b35"></u-icon>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <text class="load-text">{{ loading ? '加载中...' : '上拉加载更多' }}</text>
      </view>

      <!-- 没有更多数据 -->
      <view class="no-more" v-if="!hasMore && goodsList.length > 0">
        <text class="no-more-text">没有更多商品了</text>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="goodsList.length === 0 && !loading">
        <image class="empty-icon"
               src="https://file.casugn.com/storecompcard/temp/empty_1757670312925.png"
               mode="aspectFit"></image>
        <text class="empty-text">暂无商品</text>
        <text class="empty-desc">点击右下角按钮添加商品</text>
      </view>
    </scroll-view>

    <!-- 添加商品悬浮按钮 -->
    <view class="fab-button" @click="addGoods">
      <u-icon name="plus" size="40" color="#fff"></u-icon>
    </view>
  </view>
</template>

<script>
import {mapGetters} from 'vuex'
import userInfo from "@/pages/user/components/userInfo.vue";

export default {
  name: 'MyShopGoods',

  data() {
    return {
      goodsList: [],
      loading: false,
      hasMore: true,
      pageNo: 1,
      pageSize: 10
    }
  },

  computed: {
    ...mapGetters(['openId', 'userInfo'])
  },

  onShow() {
    this.loadGoodsList()
  },

  methods: {
    // 加载商品列表
    async loadGoodsList() {
      if (this.loading) return

      this.loading = true

      try {
        const params = {
          // openId: this.openId,
          cardId: this.userInfo.id,//用户id即为cardId
          pageNo: this.pageNo,
          pageSize: this.pageSize
        }

        console.log('获取商品列表参数:', params)

        const res = await this.$api.getGoodsList(params)

        if (res.success && res.result) {
          if (this.pageNo === 1) {
            this.goodsList = res.result.records || []
          } else {
            this.goodsList = [...this.goodsList, ...(res.result.records || [])]
          }

          // 判断是否还有更多数据
          this.hasMore = this.goodsList.length < (res.result.total || 0)

          console.log('商品列表数据:', res.result)
        } else {
          uni.showToast({
            title: res.message || '获取商品列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    // 编辑商品
    editGoods(item) {
      const id = item.id
      if (!id) return
      uni.navigateTo({
        url: `/pagesMall/myShop/addMyGoods?isNew=0&id=${id}`
      })
    },
    // 删除商品
    deleteGoods(item) {
      const id = item.id
      if (!id) return
      uni.showModal({
        title: '删除确认',
        content: '确定要删除该商品吗？',
        confirmText: '删除',
        confirmColor: '#ff6b35',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({title: '删除中', mask: true})
              const resp = await this.$api.delMyGoods(id)
              if (resp && resp.success) {
                uni.showToast({title: '删除成功', icon: 'none'})
                // 重置并刷新
                this.pageNo = 1
                this.hasMore = true
                this.loadGoodsList()
              } else {
                uni.showToast({title: resp?.message || '删除失败', icon: 'none'})
              }
            } catch (e) {
              uni.showToast({title: '删除失败', icon: 'none'})
            } finally {
              uni.hideLoading()
            }
          }
        }
      })
    },
    // 展示格式化
    formatPrice(val) {
      if (val === null || val === undefined || val === '') return '0.00'
      const num = Number(val)
      if (Number.isNaN(num)) return '0.00'
      return num.toFixed(2)
    },
    formatDiscount(val) {
      if (val === null || val === undefined || val === '') return '-'
      const num = Number(val)
      if (Number.isNaN(num)) return '-'
      return num
    },
    formatRebate(val) {
      if (val === null || val === undefined || val === '') return '-'
      const num = Number(val)
      if (Number.isNaN(num)) return '-'
      return num.toFixed(2)
    },

    // 加载更多
    loadMore() {
      if (!this.hasMore || this.loading) return

      this.pageNo++
      this.loadGoodsList()
    },

    // 跳转到商品详情
    goToGoodsDetail(item) {
      console.log('查看商品详情:', item)
      uni.navigateTo({
        url: `/pagesMall/myShop/goodsDetail?id=${item.id}`
      })
    },

    // 添加商品
    addGoods() {
      console.log('添加商品')
      uni.navigateTo({
        url: '/pagesMall/myShop/addMyGoods?isNew=1'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.goods-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  position: relative;
}

.goods-scroll {
  height: 100vh;
}

.goods-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  padding: 20rpx;
}

.goods-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  }
}

.goods-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  background-color: #f0f2f5;
  margin-right: 24rpx;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.goods-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.goods-desc {
  font-size: 24rpx;
  color: #909399;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.goods-meta {
  display: flex;
  gap: 20rpx;
  margin-top: 8rpx;
}

.meta-item {
  font-size: 24rpx;
  color: #606266;
}

.goods-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 8rpx;
}

.goods-price {
  font-size: 28rpx;
  font-weight: 600;
  color: #ff6b35;
}

.goods-stock {
  font-size: 24rpx;
  color: #606266;
}

.goods-status {
  margin-left: 20rpx;
}

.status-text {
  font-size: 24rpx;
  color: #909399;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  background-color: #f5f7fa;

  &.active {
    color: #10c469;
    background-color: rgba(16, 196, 105, 0.1);
  }
}

.item-actions {
  margin-top: 16rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.action-btn {
  display: inline-flex;
  align-items: center;
  gap: 8rpx;
  padding: 10rpx 16rpx;
  border-radius: 24rpx;
  background-color: #f5f7fa;
}

.action-btn.edit {
  background-color: rgba(65, 130, 187, 0.1);
}

.action-btn.delete {
  background-color: rgba(255, 107, 53, 0.1);
}

.action-text {
  font-size: 24rpx;
  color: #606266;
}

.load-more {
  padding: 40rpx;
  text-align: center;
}

.load-text {
  font-size: 26rpx;
  color: #909399;
}

.no-more {
  padding: 40rpx;
  text-align: center;
}

.no-more-text {
  font-size: 26rpx;
  color: #c0c4cc;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 40rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #909399;
}

.fab-button {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(74, 144, 226, 0.4);
  z-index: 1000;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.95);
    box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.4);
  }
}
</style>
